package cn.edu.swufe.surverpark.util;

import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.Action;

import cn.edu.swufe.surverpark.model.Right;
import cn.edu.swufe.surverpark.model.User;
import cn.edu.swufe.surverpark.struts2.UserAware;

/**
 * @author 陈龙 E-mail:529914446@qq.com
 * @version创建时间:2015年4月29日下午9:21:50 类说明
 */
public class ValidateUtil {
	/**
	 * 判断字符串是否有效
	 * 
	 * @param src
	 * @return boolean
	 */
	public static boolean isValid(String src) {
		// 空值返回false
		// 非空返回true
		return !(src == null || "".equals(src.trim()));
	}

	public static boolean isValid(Collection col) {
		// 空返回false
		// 非空返回true
		return !(col == null || col.isEmpty());
	}

	public static boolean isValid(Object[] arr) {
		if (arr == null || arr.length == 0)
			return false;
		return true;
	}

	public static boolean hasRight(HttpServletRequest req, String namespace,
			String actionName, Action action) {
		if (ValidateUtil.isValid(namespace) || "/".equals(namespace))
			namespace = "";
		if (actionName.contains("?"))
			actionName = actionName.substring(0, actionName.indexOf("?"));
		String url = namespace + "/" + actionName;
		HttpSession session = req.getSession();
		ServletContext sc = session.getServletContext();
		@SuppressWarnings("unchecked")
		Map<String, Right> map = (Map<String, Right>) sc
				.getAttribute("all rights map");
		Right r = map.get(url);
		if (r == null || r.isCommon()) {
			return true;
		} else {
			User user = (User) session.getAttribute("user");
			if (user == null) {
				return false;
			} else {
				if(action != null&&action instanceof UserAware){
					((UserAware) action).setUser(user);
				}
				if (user.isSuperAdmin() || user.hasRight(r)) {

					return true;
				} else {
					return false;
				}
			}
		}
	}
}
